/**
 * Created by Eoly on 2017/2/16.
 * Call http://palerock.cn
 */
var myGroupPage = angular.module('myGroupPage', ['ngRoute']);

myGroupPage.filter('beToGroupStatus', function () {
    return function (status) {
        return app.beToGroupStatus(status)
    };
});

/**
 * 我的团
 */
myGroupPage.controller('myGroup', function ($scope, $http, $route) {


    //声明请求参数
    var paramToGetGroups = {line: 0, next: 2};

    //保存获取到第几条
    app.myInitGroupLine = 0;

    //搜索筛选
    $scope.groupStatus = 'null';

    //声明获得的团数组
    $scope.groupList = [];
    $scope.suiMobileInit = function () {
        app.suiInit();
        var status = sessionStorage.getItem('ptsc_group_init_filter_status');
        if (status == null) {
            return;
        }
        $scope.groupStatus = status;
        // console.log($scope.groupStatus);
    };

    //跳转团详情页面
    $scope.turnDetail = function (group, url, sharp) {
        sessionStorage.setItem('ptsc_detail_groupId', group.groupId);
        app.turnHref(url, sharp, 'group-detail.html');
    };

    //获取团
    $scope.showUserInitGroups = function (isRefresh, isAppend, option) {

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        var url = '';
        switch (option){
            case 0:     //自己发起的团
                url = '/user/group/find-init-groups';
                break;
            case 1:     //参加的团
                url = '/user/group/show-joined-groups';
                break;
            default:
            {   // 获取所有有关的团
                url = '/user/group/show-all-groups'
            }
        }

        if (isAppend) {
            paramToGetGroups.line = app.myInitGroupLine;
            app.myInitGroupLine += paramToGetGroups.next;
            paramToGetGroups = {line: app.myInitGroupLine, next: 2};
        }

        //如若是刷新数据
        if (isRefresh) {
            paramToGetGroups = {line: 0, next: 2};
            app.myInitGroupLine = 0;
        }

        //从服务器获取团信息
        paramToGetGroups.groupStatus = $scope.groupStatus;
        // console.log($scope.groupStatus);
        if ($scope.groupStatus == null || $scope.groupStatus == 'null') {
            delete paramToGetGroups.groupStatus;
        }
        $http({
            method: 'get',
            url: net + url,
            headers: {'Authorization': 'Bearer ' + token},
            params: paramToGetGroups
        }).then(
            //响应成功
            function (res) {
                if (!res.data.error) {

                    console.log(res.data);

                    //声明一个变量暂时保存获取的团信息数组
                    var groupList = res.data.dataList;

                    //遍历团信息组,将图片地址这个属性转化为js可以识别的数组
                    for (var i = 0; i < groupList.length; i++) {
                        //声明一个imgSrc接收转化为数组的图片地址
                        groupList[i].imgSrc = eval(res.data.dataList[i].groupImgs);
                        for (var o = 0; o < groupList[i].imgSrc.length; o++) {
                            //遍历图片地址并加上服务器的url
                            groupList[i].imgSrc[o] = net + '/resources/img/' + groupList[i].imgSrc[o];
                        }
                        if (isAppend) {
                            $scope.groupList.push(groupList[i]);
                        }
                    }

                    //将之前处理好的团对象保存在scope里
                    //判断是否为追加
                    if (!isAppend) {
                        $scope.groupList = groupList;
                    }

                    console.log($scope.groupList);
                    //刷新动作
                    $.pullToRefreshDone('.pull-to-refresh-content');

                    if (isRefresh) {
                        $.toast("刷新成功", 800, "toastToBot");
                        //启用无限加载事件
                        $.attachInfiniteScroll($('.infinite-scroll'));
                        // 启用加载提示符
                        $('.infinite-scroll-preloader').show();
                    }
                    if (isAppend) {
                        loading = false;
                    }
                    //容器发生改变,如果是js滚动，需要刷新滚动
                    $.refreshScroller();

                    if($scope.groupList.length<2){
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        $.detachInfiniteScroll($('.infinite-scroll'));
                        // 删除加载提示符
                        $('.infinite-scroll-preloader').hide();
                        loading = false;
                    }
                } else {
                    if (res.data.error == 605 || res.data.error == 781) {
                        $.toast("没有更多团了", 800, "toastToBot");
                        if(isRefresh){
                            $scope.groupList = [];
                        }
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        $.detachInfiniteScroll($('.infinite-scroll'));
                        // 删除加载提示符
                        $('.infinite-scroll-preloader').hide();
                        loading = false;
                        return;
                    }
                    //刷新动作
                    $.pullToRefreshDone('.pull-to-refresh-content');
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes);
                }
                // 自动储存筛选状态
                $scope.$watch('groupStatus', function () {
                    sessionStorage.setItem('ptsc_group_init_filter_status', $scope.groupStatus);
                });
            },
            //响应失败
            function (res) {
                //刷新动作
                $.pullToRefreshDone('.pull-to-refresh-content');
                $.alert('请检查网络后重试');
            }
        );
    };

    // 改变筛选状态
    $scope.changeFilterStatus = function (op) {
        var option = [
            {
                name: '所有状态',
                value: 'null'
            },
            {
                name: '审核中',
                value: -1
            },
            {
                name: '拼团中',
                value: 0
            },
            {
                name: '拼团成功',
                value: 1
            },
            {
                name: '拼团失败',
                value: 2
            }
        ];
        app.filterOptionsAction('选择需要筛选的团状态：', option, $scope.groupStatus, function (status) {
            $scope.groupStatus = status;
            $scope.showUserInitGroups(true, false,op);
        })
    };


    // 在发团页面当点击时弹出选择列表
    $scope.makeChoiceToTurn = function (group) {
        var buttons1 = [
            {
                text: '查看团详情',
                color: 'danger',
                onClick: function() {
                    $scope.turnDetail(group,'my-group.html','#my-init-group')
                }
            },
            {
                text: '查看该团的所有订单',
                onClick: function() {
                    sessionStorage.setItem('ptsc_order_group_id',group.groupId);
                    app.turnHref('my-group.html','#my-init-group','user-order.html');
                }
            }
        ];
        var buttons2 = [
            {
                text: '取消',
                bg: 'danger'
            }
        ];
        var groups = [buttons1, buttons2];
        $.actions(groups);
    }

});
/**
 * 路由
 */
myGroupPage.config(function ($routeProvider) {
    $routeProvider.when('/my-init-group', {
        templateUrl: 'html/my-init-group-content.html',
        controller: 'myGroup'
    }).when('/my-all-group', {
        templateUrl: 'html/my-all-group-content.html',
        controller: 'myGroup'
    }).when('/my-joined-group', {
        templateUrl: 'html/my-joined-group-content.html',
        controller: 'myGroup'
    }).otherwise({
        redirectTo: '/my-all-group'
    });
});